<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox, ElTag, ElMessage } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import Edit from './components/Edit.vue'
import See from './components/See.vue'

import { Table } from '@/components/Table'

import {
  spForageFormulaListApi,
  spForageFormulaEditApi,
  spForageFormulaAddAdminApi,
  spForageFormulaDelApi,
  spForageFormulaIsStopApi
} from '@/api/sp/food'

import { useTable } from '@/hooks/web/useTableTest'
import { h, ref, reactive, unref } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'
const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })
const iconOpen = useIcon({ icon: 'material-symbols:lock-open' })
const iconClose = useIcon({ icon: 'material-symbols:lock' })
// const iconExcel = useIcon({ icon: 'file-icons:microsoft-excel' })
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
const userInfo: any = wsCache.get('userInfo')
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: spForageFormulaListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '组织名称',
    search: {
      show: true
    },
    form: {
      show: false
    }
  },
  {
    field: 'name',
    label: '配方名',
    search: {
      show: true
    }
  },
  {
    field: 'threshold',
    label: '默认阀值'
  },
  {
    field: 'note',
    label: '备注',
    search: {
      show: false
    },
    form: {
      show: true,
      componentProps: {
        placeholder: '请输入（如：适合什么阶段活畜使用）'
      }
    }
  },
  {
    field: 'is_stop',
    label: '是否启用',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return h(
        ElTag,
        {
          type: cellValue == '0' ? 'success' : cellValue == '1' ? 'warning' : 'danger'
        },
        () => (cellValue == '0' ? '启用' : cellValue == '1' ? '停用' : '未知')
      )
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.is_stop
      },
      show: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '启用',
            value: '0'
          },
          {
            label: '停用',
            value: '1'
          }
        ]
      }
    }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 170,
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'action',
    width: 200,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {}
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm(`删除该饲料配方？`, '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del(row.id)
        })
        .catch(() => {})
      break
    case 'open':
      ElMessageBox.confirm(`启用后可以使用配方，是否开启？`, '开启', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          open(row.id, '0')
        })
        .catch(() => {})
      break
    case 'close':
      ElMessageBox.confirm(`禁用后不可以使用配方，是否禁用？`, '禁用', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 归档
          open(row.id, '1')
        })
        .catch(() => {})
      break
    default:
      console.log('未知类型')
  }
}
const open = async (val, arg) => {
  let res = await spForageFormulaIsStopApi({ id: val, is_stop: arg })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (res) {
    getList()
  }
}
const del = async (val) => {
  let res = await spForageFormulaDelApi({ id: val })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (res) {
    getList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()
const loading = ref(false)
const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const data = (await edit?.getFormData()) as any
          let a: Number = 0
          data.detailed.forEach((element) => {
            if (element.forage_id) {
              a = Number(element.ratio) + Number(a)
            } else {
              return ElMessage({
                message: '饲料不能为空',
                type: 'warning'
              })
            }
          })
          if (a == 100) {
            loading.value = true
            let res = await spForageFormulaEditApi(data)
              .catch(() => {})
              .finally(() => {
                loading.value = false
              })
            if (res) {
              dialogVisible.value = false
              tableObject.currentPage = 1
              getList()
            }
          } else {
            loading.value = false
            ElMessage({
              message: '饲料配比不符合规定',
              type: 'warning'
            })
          }
        }
      })
      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          const data = (await edit?.getFormData()) as any
          data.my_dept_id = userInfo.default_dept_id
          let a: Number = 0
          data.is_stop = '0'
          data.detailed.forEach((element) => {
            if (element.forage_id) {
              a = Number(element.ratio) + Number(a)
              console.log(element.ratio, 'element.ratio', a, 'a')
            } else {
              return ElMessage({
                message: '饲料不能为空',
                type: 'warning'
              })
            }
          })
          if (a == 100) {
            loading.value = true
            let res = await spForageFormulaAddAdminApi(data)
              .catch(() => {})
              .finally(() => {
                loading.value = false
              })
            if (res) {
              dialogVisible.value = false
              tableObject.currentPage = 1
              getList()
            }
          } else {
            loading.value = false
            ElMessage({
              message: '饲料配比不符合规定',
              type: 'warning'
            })
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}
const { allSchemas } = useCrudSchemas(crudSchemas)
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
    </div>
    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      :selection="false"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconEdit" @click="action('edit', row)" title="编辑" />
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <ElButton circle :icon="iconDel" @click="action('del', row)" title="删除" />
        <!-- <ElButton circle :icon="iconExcel" @click="action('excel', row)" title="导出" /> -->
        <ElButton
          v-if="row.is_stop == 1"
          circle
          :icon="iconOpen"
          @click="action('open', row)"
          title="启用"
        />
        <ElButton
          v-if="row.is_stop == 0"
          circle
          :icon="iconClose"
          @click="action('close', row)"
          title="停用"
        />
      </template>
    </Table>
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit v-if="actionType == 'add'" ref="editRef" :form-schema="allSchemas.formSchema" />
    <Edit
      v-if="actionType == 'edit'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :id="tableObject.currentRow.id"
    />
    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :id="tableObject.currentRow.id"
    />
    <template #footer>
      <ElButton
        v-if="actionType == 'edit' || actionType == 'add'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>
